<script setup >
import navbar from './components/Navbar.vue'
import Carousel from '@/components/Carousel/Carousel.vue'
import CateScroll from "@/components/CateScroll/CateScroll.vue";
import HotsRecommend from "@/components/HotsRecommend/HotsRecommend.vue";
import NewGoods from "@/components/NewGoods/NewGoods.vue";
import HostBrand from "@/components/HostBrand/HostBrand.vue";
import Guess from "@/components/Guess/Guess.vue";
import { getBannersAPI, getCategoryAPI, getHotsAPI, getNewGoodsAPI, getLikesAPI } from "@/api/home";
import { ref } from 'vue';



//#region 轮播图
const banners = ref([])
const loadBanners = async () => {
  const res = await getBannersAPI()
  banners.value = res.result
}
loadBanners()
//#endregion

//#region 前台类名
const category = ref([])
const loadCategory = async () => {
  const res = await getCategoryAPI()
  category.value = res.result
}
loadCategory()
//#endregion

//#region 人气推荐
const hots = ref([])
const loadHots = async () => {
  const { result } = await getHotsAPI()
  hots.value = result
}
loadHots()
//#endregion

//#region 新鲜好物
const newGoods = ref([])
const loadNewGoods = async () => {
  const { result } = await getNewGoodsAPI()
  newGoods.value = result
}
loadNewGoods()
//#endregion

//#region 猜你喜欢
const likes = ref([])
const page = ref(1) //当前页
const pages = ref(1) //总页数
const loadLikes = async () => {
  const { result } = await getLikesAPI(page.value)
  page.value++
  pages.value = result.pages
  likes.value = [...likes.value, ...result.items]
}
loadLikes()
//滚动条触底事件
const loadMore = () => {
  if (page.value > pages.value) {
    uni.showToast({ title: "没有更多数据啦！", icon: "none" })
    return
  }
  loadLikes();
}
//#endregion

//#region 下拉刷新
//下拉刷新已经被触发
const refresherTriggered = ref(false)
//下拉触发
const onRefresherRefresh = async () => {
  console.log('上拉啦');
  refresherTriggered.value = true
  page.value = 1
  likes.value = []
  // 使用promise的api,同时运行异步操作，等await执行完成才往下执行
  await Promise.all([loadBanners(), loadCategory(), loadLikes(),loadHots(),loadNewGoods()])
  //下拉刷新未被触发
  refresherTriggered.value = false
}
//#endregion


</script>

<template>
  <!-- 修复样式，添加content -->
  <view class="content">
    <navbar />
    <!-- 修复样式，添加main -->
    <scroll-view scroll-y class="main" @scrolltolower="loadMore" refresher-enabled @refresherrefresh="onRefresherRefresh"
      :refresher-triggered="refresherTriggered">
      <!-- 轮播图 -->
      <Carousel v-if="banners.length > 0" :banners="banners" height="280rpx" />
      <!-- 分类栏目 -->
      <CateScroll v-if="category.length > 0" :category="category" />
      <!--  人气推荐 -->
      <HotsRecommend :hots="hots" />
      <!-- 新鲜好物 -->
      <NewGoods :newGoods="newGoods" />
      <!-- 热门品牌 -->
      <HostBrand />
      <!-- 猜你喜欢 -->
      <Guess :list="likes" />
    </scroll-view>
  </view>
</template>

<style lang="scss" scoped>
.content {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.main {
  flex: 1;
  overflow: hidden;
  background-color: #f7f7f8;
}
</style>

